<template>
  <div>
    <!-- 产品管理弹窗 -->
    <t-dialog :visible.sync="visible" :width="680" :footer="false" :closeBtn="false">
      <div slot="header">{{ title }}</div>
      <div slot="body">
        <t-divider :style="{ marginTop: '1px' }"></t-divider>
        <!-- 表单内容 -->
        <t-form :data="formDataExePlan" ref="form" :rules="rules" @submit="commit" :labelWidth="100">
          <t-form-item label="测试计划名称" name="testplan_name">
            <t-input readonly :style="{ width: '480px' }" v-model="formDataExePlan.testplan_name" placeholder="请输入测试计划名称"></t-input>
          </t-form-item>
          <t-form-item label="运行的链" name="chain">
            <t-select v-model="formDataExePlan.chain_id" :style="{ width: '480px' }" class="demo-select-base" clearable filterable placeholder="请选择运行的链" @change="onChainSelect">
              <t-option v-for="(item, index) in options" :value="item.value" :label="item.label" :key="index">
                {{ item.label }}
              </t-option>
            </t-select>
          </t-form-item>
          <t-form-item label="接受节点" name="node_ip_list" v-if="formDataExePlan.chain_id">
<!--            <t-checkbox-group v-model="node_ip_list" :options="selectedChainNodes" @change="onChange" />-->
            <t-checkbox-group v-model="selectedNodes" :options="formattedSelectedChainNodes" @change="onChange" />
          </t-form-item>
          <t-form-item style="float: right">
            <t-button variant="outline" @click="onCancel" :style="{ marginRight: '10px' }">取消</t-button>
            <t-button theme="primary" type="submit">确定</t-button>
          </t-form-item>
        </t-form>
      </div>
    </t-dialog>
  </div>
</template>

<script>
export default {
  name: "ExePlanDialog",
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    title: {
      type: String,
      required: true,
    },

  },
  data() {
    return {
      rules: {
        // 表单验证规则
      },
      formDataExePlan: { ...this.formData }, // 将父组件传递的数据赋值给formDataAddHost
      options: [],
      selectedChainNodes: [],
      node_ip_list:[],
      node:[],
      selectedNodes: [],
    };
  },
  computed: {
    formattedSelectedChainNodes() {
      return this.selectedChainNodes.map(node => ({
        label: node.node_name,
        value: node.node_addr,
      }));
    },
  },
  watch: {
    visible(newVal) {
      this.visible = newVal;
    },
    formData(newVal) {
      this.formDataExePlan = { ...newVal }; // 监听父组件传递的数据变化，并更新formDataAddHost
    },
  },
  mounted() {
    this.visible = this.visible;
    this.formDataExePlan = { ...this.formData };
    this.loadChain();
    console.log('dataSource--->', this.dataSource);
    // 在页面加载时，默认选择第一个链并获取其节点列表
    if (this.dataSource !== undefined && this.dataSource.length > 0) {
      this.formDataExePlan.chain_id = this.dataSource[0].id;
      this.onChainSelect();
    }
  },

  methods: {
    loadChain() {
      this.$request
        .get('/api/query/chains_conn_list')
        .then((res) => {
          // console.log("获取到当前所有的链", JSON.stringify(res.data))
          if (res.data.code === '000') {
            // console.log("拿到了所有的链了吗？？？？", JSON.stringify(res.data.data))
            this.dataSource = res.data.data
            console.log('dataSource1--->', this.dataSource);
            this.options = this.dataSource.map(chain => ({
              label: chain.name,
              value: chain.id
            }));
            if (this.dataSource.length > 0) {
              this.selectedChainNodes = this.dataSource[0].node_list;
              // console.log('selectedChainNodes--->',this.selectedChainNodes )
            }
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    handleCheckedChange({ checked, sourceChecked, targetChecked, type }) {
      console.log("handleCheckedChange", {
        checked,
        sourceChecked,
        targetChecked,
        type,
      });
      console.log(this.targetValue, "targetValue");
    },
    handlePageChange(...args) {
      console.log('handlePageChange', args);
    },
    commit() {
      // console.log("this.formDataExePlan~~~~~~",this.formDataExePlan)
      let params = {};
      if (this.formDataExePlan.id) {
        // 存在 id 字段，表示可以执行测试计划id
        params = {
          testplan_name: this.formDataExePlan.testplan_name,
          chain_id:this.formDataExePlan.chain_id,
          node_list:this.node_ip_list,
          id: this.formDataExePlan.id
        };
      } else {
        // 不存在 id 字段，表示不能执行
        this.$message.warning("测试计划id不存在");
      }
      // console.log('执行测试计划的参数:', params);

      this.$request
        .post('/api/exe/testplan', params)
        .then((res) => {
          this.$message.success('提交成功');
          // 关闭弹窗
          this.$emit('cancel');
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onCancel() {
      // 处理弹窗取消事件
      this.$emit('cancel'); // 触发 cancel 事件
    },
    // 选择链的事件绑定，不同的链有不同的nodelist
    // onChainSelect() {
    //   const selectedChain = this.dataSource.find(chain => chain.id === this.formDataExePlan.chain_id);
    //   if (selectedChain) {
    //     console.log("Selected chain:", selectedChain);
    //     this.selectedChainNodes = selectedChain.node_list.map(node => ({
    //       label: node.node_name,
    //       value: node.node_addr
    //     }));
    //     // this.node_ip_list = []; // 清空已选节点列表
    //     console.log("Selected chain nodes~~~~~:", JSON.stringify(this.selectedChainNodes));
    //   }else {
    //     this.selectedChainNodes = []; // 如果没有选择链，清空节点列表
    //     this.node_ip_list = []; // 同时清空接受节点列表
    //   }
    //
    // },
    // onChange(val) {
    //   this.node_ip_list = val
    //   console.log("我勾选的ip是多少呢~~~~~", val);
    //
    //
    // },
    onChainSelect() {
      const selectedChain = this.dataSource.find(chain => chain.id === this.formDataExePlan.chain_id);
      if (selectedChain) {
        this.selectedChainNodes = JSON.parse(selectedChain.node_list);
        this.selectedNodes = []; // 清空已选节点列表
      }
    },
    onChange(val) {
      this.node_ip_list = this.selectedChainNodes.filter(node => val.includes(node.node_addr));
      // console.log("我勾选的节点数据是：", this.node_ip_list);
    },
  },
}

</script>

<style scoped>

</style>
